import axios from 'axios';
// import ajaxDebounceCreator from './ajaxDebounce';
// import storage from './Storage';

class FetchCreator {
  constructor({ ajaxBaseUrl = '', ajaxTimeout = 6000, tokenCache = 'session' }) {
    // init config
    this.ajaxConfig = {
      baseURL: ajaxBaseUrl,
      timeout: ajaxTimeout
    };
    // init create axios
    this.CancelToken = axios.CancelToken;
    this.isCancel = axios.CancelToken;
    this.tokenCache = tokenCache;
    this.axios = axios.create(this.ajaxConfig);
    this.initAxiosInterceptors(); // init axios Interceptors
    // this.fetch = ajaxDebounceCreator(this.axios);
  }

  get(url, data, options) {
    return this.axios({
      method: 'get',
      url,
      data,
      options
    });
  }

  post(url, data, options) {
    // console.log(url, data, options);
    // axios({
    //   method: 'post',
    //   url: 'http://39.105.37.134/mxb/services/usm/login/',
    //   headers: {
    //     'Content-type': 'application/x-www-form-urlencoded'
    //   },
    //   data: {
    //     userName: '222',
    //     password: '2323'
    //   },
    //   transformRequest: [
    //     (data) => {
    //       let ret = '';
    //       for (const it in data) {
    //         ret += `${encodeURIComponent(it)}=${encodeURIComponent(data[it])}&`;
    //       }
    //       return ret;
    //     }
    //   ]
    // })
    // const formData = new FormData();
    // formData.append('userName', '222');
    // formData.append('password', '33');
    // fetch('http://39.105.37.134/mxb/services/usm/login/', {
    //   method: 'POST',
    //   body: formData
    // })

    return this.axios({
      method: 'post',
      headers: {
        'Content-type': 'application/x-www-form-urlencoded'
      },
      url,
      data,
      transformRequest: [
        (data) => {
          console.log('data', data);
          // if (!options._json) {
          console.log('http request params', data);
          let ret = '';
          for (const it in data) {
            ret += `${encodeURIComponent(it)}=${encodeURIComponent(
              typeof data[it] === 'object' ? JSON.stringify(data[it]) : data[it]
            )}&`;
          }
          return ret;
          // }
          // return data;
        }
      ],
      ...options
    });
  }

  put(url, data, options) {
    return this.axios({
      method: 'put',
      url,
      data,
      ...options
    });
  }

  patch(url, data, options) {
    return this.axios({
      method: 'patch',
      url,
      data,
      ...options
    });
  }

  delete(url, data, options) {
    return this.axios({
      method: 'delete',
      url,
      data,
      ...options
    });
  }

  initAxiosInterceptors() {
    this.axios.interceptors.request.use(
      async (config) => {
        try {
          const sessionId = await READ_CACHE('sessionId');
          config.data = {
            sessionId,
            ...config.data
          };
        } catch (error) {
          //
        }
        console.log('http request:', config);
        return config;
      },
      (error) => {
        // Do something with request error
        console.log(error); // for debug
        return Promise.reject(error);
      }
    );
    // respone拦截器
    this.axios.interceptors.response.use(
      (response) => {
        try {
          const { sessionId } = response.data;
          sessionId && WRITE_CACHE('sessionId', sessionId || ''); // 保存sessionId
        } catch (error) {
          //
        }
        console.log('http response:', response);
        return response;
      },
      error => Promise.reject(error)
    );
  }
}

export default FetchCreator;
